﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TesteSharepointNovo.Models;
using WebMatrix.WebData;
using TesteSharepointNovo.Filters;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Data;
using System.IO;
using System.Net.Mail;
using System.Web.Routing;

namespace TesteSharepointNovo.Controllers
{
    public class HomeController : Controller
    {
        DefaultConnection db = new DefaultConnection();
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }
        public ActionResult Planos()
        {


            return View();
        }
        /// <summary>
        /// This view is used convert the DetailedReport view into a Word Document and send it to the user
        /// This Controller does not have an associated View
        /// <summary>
        public ActionResult ConverterParaWord(int id)
        {
            RouteValueDictionary rvd = new RouteValueDictionary();
            rvd.Add("id", id);
            string url = Url.Action("ExibeCurriculo","Home", new { id=id},"http");
            return new WordActionResult(url, "Curriculo.doc");
        }
        public ActionResult ExibeCurriculo(int id)
        {
            var cv = db.Curriculos.Where(c => c.Id == id).Single();
     
            var result = new CurriculoViewModel();

            
            result.PodeEditar = Request.IsAuthenticated && WebSecurity.CurrentUserId == cv.UserId;
            result.CargoPretendido = cv.CargoPretendido;
            result.DataNascimento = cv.DataNascimento;
            result.Certficacoes = ObterCertificacoes(cv.Id);
            result.Endereco = cv.Endereco;
            result.Email = cv.Email;
            result.EstadoCivil = cv.EstadoCivil;
            result.Experiencias = ObterExperiencias(cv.Id);
            result.Formacoes = ObterFormacoes(cv.Id);
            result.Nacionalidade = cv.Nacionalidade;
            result.Naturalidade = cv.Naturalidade;
            result.Resumo = cv.Resumo;
            result.Tecnologias = ObterTecnologias(cv.Id);
            result.Telefone = cv.Telefone;
            result.Nome = cv.Nome;
            result.Id = cv.Id;
            return View(result);
        }
        public ActionResult EntrarContato()
        {
            return View();
        }
        [HttpPost]
        public ActionResult CriarCurriculo(Curriculo cv)
        {
            if (cv.Id != 0)
            {
                db.Entry(cv).State = EntityState.Modified;
                db.SaveChanges();
                //tecno.Curriculo = db.Curriculos.Find(tecno.Curriculo.Id);
            }
            else
            {
                cv.UserId = WebSecurity.CurrentUserId;
                db.Curriculos.Add(cv);
                db.SaveChanges();
            }
            
            return RedirectToAction("ExibeCurriculo", new { id=cv.Id});
        }
        [Authorize]
        public ActionResult CriarCurriculo()
        {

            return View();
        }
        public FileStreamResult ConverterParaPdf(int id)
        {
            MemoryStream ms = new MemoryStream();

            // create an API client instance
            pdfcrowd.Client client = new pdfcrowd.Client("rochagasdiniz", "5062f21e417515a80772b7972f2b6262");

            client.setPageWidth(940);
            // convert a web page and save the PDF to a file
            //ms = new FileStream("google_com.pdf", FileMode.CreateNew);
            client.convertURI("http://curriculo.apphb.com/Home/ExibeCurriculo?id="+id, ms);
            
            return new FileStreamResult(ms, "application/pdf")
            {
                FileDownloadName = "curriculo.pdf"
            }; 
        }
        [HttpPost]
        public ActionResult EntrarContato(string nome,string email,string message)
        {
          
            if (string.IsNullOrEmpty(email))
            {
                ModelState.AddModelError("email", "Preencha o seu email");
                return View();
            }
            if (string.IsNullOrEmpty(message))
            {
                ModelState.AddModelError("message", "Preencha a messagem");
                return View();
            }

            var smtpClient = new SmtpClient();
            smtpClient.Send(email, "rochagasdiniz@gmail.com", "Curriculo", message);
            return RedirectToAction("Contact");
        }
        public ActionResult About()
        {
           
            var user = WebSecurity.GetUserId("rochagasdiniz");

            var cv = db.Curriculos.FirstOrDefault();
            cv.UserId = user;
            db.SaveChanges();
            return View();
        }
        //[InitializeSimpleMembership]
        //private void popula()
        //{
        //    var db = new DefaultConnection();
            
        //    var user = WebSecurity.GetUserId("rochagasdiniz");
        //    var cv = new Curriculo
        //    {
        //        CargoPretendido = "Analista Programador .net",
        //        DataNascimento= new DateTime(1973,3,22),
        //        Endereco="Rua das Laranjeiras - Laranjeiras - RJ",
        //        EstadoCivil=" Casado 1 Filho",
        //        Nacionalidade="Brasileiro",
        //        Naturalidade= "São Paulo",
        //        Nome="Rodrigo do Valle Chagas Diniz",
        //        Resumo = " <ul> <li>Desde 1999 trabalhando com desenvolvimento para a web. </li>" +
        //               " <li>Desde 2003 trabalhando com asp.net (C Sharp)</li>" +
        //               " <li>Vasta experiência em desenvolvimento de stored procedures tanto em t-sql como pl-sql</li>" +
        //               " <li>Responsável pelo desenvolvimento e implantação de diversos projetos ASP. NET em C Sharp</li>" +
        //               " <li>Responsável pelo desenvolvimento de sistemas utilizando asp.net mvc, e Jquery.</li>" +
        //              "  <li>Coordenador e principal desenvolvedor do projeto http://www.codeplex.com/ExtJsExtenderControl </li></ul>",
        //        Telefone=string.Empty,
        //        UserId= user
        //    };
        //    db.Curriculos.Add(cv);
        //    try
        //    {
        //        db.SaveChanges();
        //    }
        //    catch (DbEntityValidationException dbEx)
        //    {
        //        foreach (var validationErrors in dbEx.EntityValidationErrors)
        //        {
        //            foreach (var validationError in validationErrors.ValidationErrors)
        //            {
        //                Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
        //            }
        //        }
        //    }
           
        //}

        private void CarregaExperiencia(){
            var db = new DefaultConnection();
            var cv = db.Curriculos.FirstOrDefault();
            
        }
        public ActionResult EditarTecnologia(int idCurriculo, int? idTecno)
        {

            var cv = db.Curriculos.Find(idCurriculo);
            var experiencia = new Tecnologia { Curriculo = cv };
            if (idTecno.HasValue)
            {
                experiencia = db.Tecnologias.Find(idTecno.Value);
            }
            return View(experiencia);
        }
        [HttpPost]
        public ActionResult EditarTecnologia(Tecnologia tecno)
        {
            if (tecno.Id != 0)
            {
                db.Entry(tecno).State = EntityState.Modified;
                tecno.Curriculo = db.Curriculos.Find(tecno.Curriculo.Id);
            }
            else
            {
                //exp.Curriculo= db.Curriculos.Find(exp.)
                tecno.Curriculo = db.Curriculos.Find(tecno.Curriculo.Id);
                db.Tecnologias.Add(tecno);
            }
            try
            {

                db.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }

            return RedirectToAction("Contact");
        }

        public ActionResult ExcluirExperiencia(int id)
        {
            var exp=db.Experiencias.Find(id);
            db.Experiencias.Remove(exp);
            db.SaveChanges();
            return RedirectToAction("Contact");
        }
        public ActionResult EditarLingua(int idCurriculo, int? idExperiencia)
        {
            var cv = db.Curriculos.Find(idCurriculo);
            var experiencia = new Lingua { Curriculo = cv };
            if (idExperiencia.HasValue)
            {
                experiencia = db.Linguas.Find(idExperiencia.Value);
            }
            return View(experiencia);
        }

        [HttpPost]
        public ActionResult EditarLingua(Lingua exp)
        {
            if (exp.Id != 0)
            {
                exp.Curriculo = db.Curriculos.Find(exp.Curriculo.Id);
                db.Entry(exp).State = EntityState.Modified;

                //exp.Curriculo = db.Curriculos.Find(exp.Curriculo.Id);
            }
            else
            {

                exp.Curriculo = db.Curriculos.Find(exp.Curriculo.Id);
                db.Linguas.Add(exp);
            }
            try
            {

                db.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }

            return RedirectToAction("Contact");
        }

        public ActionResult EditarExperiencia(int idCurriculo, int? idExperiencia)
        {
            var cv = db.Curriculos.Find(idCurriculo);
            var experiencia= new Experiencia{Curriculo =cv};
            if (idExperiencia.HasValue)
            {
                experiencia = db.Experiencias.Find(idExperiencia.Value);
            }
            return View(experiencia);
        }
        public ActionResult EditarCertificacao(int idCurriculo, int? idCertificacao)
        {
            var cv = db.Curriculos.Find(idCurriculo);
            var experiencia = new Certificacao { Curriculo = cv };
            if (idCertificacao.HasValue)
            {
                experiencia = db.Certificacoes.Find(idCertificacao.Value);
            }
            return View(experiencia);
        }
        public ActionResult EditarFormacao(int idCurriculo, int? idFormacao)
        {
            var cv = db.Curriculos.Find(idCurriculo);
            var experiencia = new Formacao { Curriculo = cv };
            if (idFormacao.HasValue)
            {
                experiencia = db.Formacoes.Find(idFormacao.Value);
            }
            return View(experiencia);
        }
        [HttpPost]
        public ActionResult EditarCertificacao(Certificacao exp)
        {
            if (exp.Id != 0)
            {
                exp.Curriculo = db.Curriculos.Find(exp.Curriculo.Id);

                if (Request.Files.Count >0)
                {
                    byte[] fileData = null;

                    using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
                    {
                        fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
                    }
                    exp.Logo = fileData;
                }
                db.Entry(exp).State = EntityState.Modified;

                //exp.Curriculo = db.Curriculos.Find(exp.Curriculo.Id);
            }
            else
            {
                if (Request.Files.Count > 0)
                {
                    byte[] fileData = null;

                    using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
                    {
                        fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
                    }
                    exp.Logo = fileData;
                }
                exp.Curriculo = db.Curriculos.Find(exp.Curriculo.Id);
                db.Certificacoes.Add(exp);
            }
            try
            {

                db.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }

            return RedirectToAction("Contact");
        }
        [HttpPost]
        public ActionResult EditarFormacao(Formacao exp)
        {
            if (exp.Id != 0)
            {
                exp.Curriculo = db.Curriculos.Find(exp.Curriculo.Id);
                db.Entry(exp).State = EntityState.Modified;

                //exp.Curriculo = db.Curriculos.Find(exp.Curriculo.Id);
            }
            else
            {
               
                exp.Curriculo = db.Curriculos.Find(exp.Curriculo.Id);
                db.Formacoes.Add(exp);
            }
            try
            {

                db.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }

            return RedirectToAction("Contact");
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditarExperiencia(Experiencia exp)
        {
            if (exp.Id!=0)
            {
                exp.Curriculo = db.Curriculos.Find(exp.Curriculo.Id);
                if (exp.Atual)
                {
                    exp.AnoFinal = DateTime.Now.Year;
                    exp.MesFinal = DateTime.Now.Month;
                }
                db.Entry(exp).State = EntityState.Modified;
                
                //exp.Curriculo = db.Curriculos.Find(exp.Curriculo.Id);
            }
            else
            {
                if (exp.Atual)
                {
                    exp.AnoFinal = DateTime.Now.Year;
                    exp.MesFinal = DateTime.Now.Month;
                }
                exp.Curriculo = db.Curriculos.Find(exp.Curriculo.Id);
                db.Experiencias.Add(exp);
            }
            try
            {
               
                db.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }
            }
           
            return RedirectToAction("Contact");
        }
        private List<Experiencia> ObterExperiencias(int idCV)
        {
            return db.Experiencias.Where(c => c.Curriculo.Id == idCV)
                .OrderByDescending(c=>c.AnoFinal)
                .ThenByDescending(c=>c.AnoInicio).ToList();
        }

        private List<Certificacao> ObterCertificacoes(int idCV)
        {
            return db.Certificacoes.Where(c => c.Curriculo.Id == idCV).ToList();
               
               
        }
        private List<Lingua> ObterLinguas(int idCV)
        {
            return db.Linguas.Where(c => c.Curriculo.Id == idCV).ToList();


        }
        private List<Tecnologia> ObterTecnologias(int idCV)
        {
            return db.Tecnologias.Where(c => c.Curriculo.Id == idCV).ToList();
              
        }
        private List<Formacao> ObterFormacoes(int idCV)
        {
            return db.Formacoes.Where(c => c.Curriculo.Id == idCV).ToList();

        }
        
        [OutputCache(Duration = int.MaxValue, VaryByParam = "id")]
        public FileContentResult getImg(int id)
        {
            byte[] byteArray = db.Certificacoes.Find(id).Logo;
            if (byteArray != null)
            {
                return new FileContentResult(byteArray, "image/jpeg");
            }
            else
            {
                return null;
            }
        }
        //[OutputCache(Duration = int.MaxValue, VaryByParam = "id")]
        public ActionResult Contact()
        {
            
            var cv = db.Curriculos.FirstOrDefault();
          
            
            var result = new CurriculoViewModel();
           
            //if (cv == null)
            //{
            //    popula();
            //    cv = db.Curriculos.FirstOrDefault();
            //}
            result.PodeEditar = Request.IsAuthenticated && WebSecurity.CurrentUserId == cv.UserId ;
            result.CargoPretendido = cv.CargoPretendido;
            result.DataNascimento = cv.DataNascimento;
            result.Certficacoes = ObterCertificacoes(cv.Id);
            result.Endereco = cv.Endereco;
            result.Email = cv.Email;
            result.EstadoCivil = cv.EstadoCivil;
            result.Experiencias = ObterExperiencias(cv.Id);
            result.Formacoes = ObterFormacoes(cv.Id);
            result.Nacionalidade = cv.Nacionalidade;
            result.Naturalidade = cv.Naturalidade;
            result.Resumo = cv.Resumo;
            result.Tecnologias = ObterTecnologias(cv.Id);
            result.Telefone = cv.Telefone;
            result.Nome = cv.Nome;
            result.Id = cv.Id;
            result.Linguas = ObterLinguas(cv.Id);
            return View(result);
        }
    }
}
